package apptoko.com.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Typeface;
import android.support.v4.widget.CursorAdapter;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import apptoko.com.adapter.DownloadItemView.DownloadSelectListener;
import apptoko.com.download.DownloadManager;

import com.androidquery.AQuery;
import apptoko.com.R;
;

public class DownloadingAdapter extends CursorAdapter {

	private Context mContext;
	private Cursor mCursor;
	private Resources mResources;

	private int mUriColumnId;
	private int mDescColumnId;
	private int mTitleColumnId;
	private int mStatusColumnId;
	private int mReasonColumnId;
	private int mTotalBytesColumnId;
	private int mCurrentBytesColumnId;
	private int mIdColumnId;
	private DownloadSelectListener mDownloadSelectionListener;
	
	private AQuery aq;
	private Typeface robotoBoldCond;

	@SuppressWarnings("deprecation")
	public DownloadingAdapter(Context context, Cursor cursor,
			DownloadSelectListener selectionListener) {
		super(context, cursor);
		// TODO Auto-generated constructor stub
		mContext = context;
		mCursor = cursor;
		mDownloadSelectionListener = selectionListener;
		mResources = context.getResources();
		mUriColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
		mDescColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_DESCRIPTION);
		mIdColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
		mTitleColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
		mStatusColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
		mReasonColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);
		mTotalBytesColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
		mCurrentBytesColumnId = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
		robotoBoldCond = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_bold_condensed));
	}

	@Override
	public void bindView(View convertView, Context context, Cursor cursor) {
		// TODO Auto-generated method stub
		if (!(convertView instanceof DownloadItemView)) {
			return;
		}
		final long downloadId = mCursor.getLong(mIdColumnId);
		((DownloadItemView) convertView).setDownloadId(downloadId);
		
		// Retrieve the icon for this download
		retrieveAndSetIcon(convertView);

		String title = mCursor.getString(mTitleColumnId);
		long totalBytes = mCursor.getLong(mTotalBytesColumnId);
		long currentBytes = mCursor.getLong(mCurrentBytesColumnId);
		int status = mCursor.getInt(mStatusColumnId);

		if (title.length() == 0) {
			title = mResources.getString(R.string.missing_title);
		}
		setTextForView(convertView, R.id.download_title, title);

		int progress = getProgressValue(totalBytes, currentBytes);

		boolean indeterminate = status == DownloadManager.STATUS_PENDING;
		ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.download_progress);
		progressBar.setIndeterminate(indeterminate);
		if (!indeterminate) {
			progressBar.setProgress(progress);
		}
		if (status == DownloadManager.STATUS_FAILED || status == DownloadManager.STATUS_SUCCESSFUL) {
			progressBar.setVisibility(View.INVISIBLE);
		} else {
			progressBar.setVisibility(View.VISIBLE);
		}
		setTextForView(convertView, R.id.download_speed, getSizeText(currentBytes, totalBytes, progress));
		setTextForView(convertView, R.id.status_text,mResources.getString(getStatusStringId(status)));
		CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.download_checkbox);
		checkBox.setChecked(mDownloadSelectionListener.isDownloadSelected(downloadId));
	}

	private String getSizeText(long downloadedBytes, long totalBytes, int progress) {
		String sizeText = "";
		if (totalBytes >= 0) {
			if(progress < 100){
				String downloadedSize = Formatter.formatFileSize(mContext, downloadedBytes);
				String totalSize = Formatter.formatFileSize(mContext, totalBytes); 
				sizeText = downloadedSize + "/" + totalSize + " (" + progress + "%)";
			} else {
				sizeText = Formatter.formatFileSize(mContext, totalBytes); 
			}
		}
		return sizeText;
	}

	private int getStatusStringId(int status) {
		switch (status) {
		case DownloadManager.STATUS_FAILED:
			return R.string.download_error;

		case DownloadManager.STATUS_SUCCESSFUL:
			return R.string.download_success;

		case DownloadManager.STATUS_PENDING:
		case DownloadManager.STATUS_RUNNING:
			return R.string.download_running;

		case DownloadManager.STATUS_PAUSED:
			if (mCursor.getInt(mReasonColumnId) == DownloadManager.PAUSED_QUEUED_FOR_WIFI) {
				return R.string.download_queued;
			} else {
				return R.string.download_paused;
			}
		}
		throw new IllegalStateException("Unknown status: "
				+ mCursor.getInt(mStatusColumnId));
	}

	private void retrieveAndSetIcon(View convertView) {
		String mimeType = mCursor.getString(mUriColumnId).substring(mCursor.getString(mUriColumnId).lastIndexOf(".") + 1, mCursor.getString(mUriColumnId).length());
		ImageView iconView = (ImageView) convertView.findViewById(R.id.download_icon);
		iconView.setVisibility(View.VISIBLE);
		if (mimeType == null) {
			return;
		}
		aq = new AQuery(convertView);
		if(mimeType.equalsIgnoreCase("apk")){
			String iconUrl = mCursor.getString(mDescColumnId);
			aq.id(iconView).image(iconUrl, true, true, 0, R.drawable.ic_launcher);
		} else if(mimeType.equalsIgnoreCase("epub")){
			aq.id(iconView).image(R.drawable.ic_book_store);
		} else if(mimeType.equalsIgnoreCase("zip")){
			aq.id(iconView).image(R.drawable.ic_comic_store);
		} else {
			aq.id(iconView).image(R.drawable.ic_launcher);
		}
		iconView.setVisibility(View.VISIBLE);
	}

	private void setTextForView(View parent, int textViewId, String text) {
		TextView view = (TextView) parent.findViewById(textViewId);
		if(textViewId == R.id.download_title){
			view.setTypeface(robotoBoldCond);
		}
		view.setText(text);
	}

	public int getProgressValue(long totalBytes, long currentBytes) {
		if (totalBytes == -1) {
			return 0;
		}
		return (int) (currentBytes * 100 / totalBytes);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup vg) {
		// TODO Auto-generated method stub
		DownloadItemView view = (DownloadItemView) LayoutInflater.from(mContext).inflate(R.layout.download_list_item, null);
		view.setSelectListener(mDownloadSelectionListener);
		return view;
	}

}
